<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;

use app\common\library\Sms;

/**
 * 会员中心
 */
class User extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register', 'third','forgetpwd'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        $ucenter = get_addon_info('ucenter');
        if ($ucenter && $ucenter['state']) {
            include ADDON_PATH . 'ucenter' . DS . 'uc.php';
        }

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->view->assign('title', __('User center'));
        
        // 所有算力
        // $all_money = model('MoneyLog')->where('user_id', $this->auth->id)->group('type')->column('type, sum(money)');
        
        $all_money = [];
        // 等级配置信息
        $group_list = db('UserGroup')->column('id, static_rate, dynamic_max_num');
        $all_money[1] = $this->auth->score*$group_list[$this->auth->group_id]['static_rate']/100;



        //财富宝资产+智能宝资产总量小于此设置时，动态算力自动停止。
        $user_min_total_bkc = (int)config::get('site.user_min_total_bkc');

        // 共享算力比例
        $share_rebate_rate = (float)config::get('site.share_rebate_rate');
        // 共享算力 所有团队的业绩
        $listTeamAmount = model('User')->getTeamAmount();


        // 分享算力
        $map = [
            'u1.id'=>$this->auth->id,
        ];
        // 达到分享算力条件的会员的2星下线数
        // $listChildNum = db('User u1')->join('__USER__ u2', 'u1.id=u2.parent_id')->where($map)->where(['u2.group_id'=>['egt', 3]])->where('u1.score+u1.money>='.$user_min_total_bkc)->group('u1.id')->having('child_num>0')->column('u1.id, count(u2.id) as child_num');
        $listChildNum = db('User u1')->join('__USER__ u2', 'u1.id=u2.parent_id')->where($map)->where(['u2.group_id'=>['egt', 3]])->group('u1.id')->having('child_num>0')->column('u1.id, count(u2.id) as child_num');

        // 达到分享算力条件的会员
        // $list = db('User u1')->field('u1.id, u1.group_id, u1.money')->where($map)->where('u1.score+u1.money>='.$user_min_total_bkc)->select();
        $list = db('User u1')->field('u1.id, u1.group_id, u1.money')->where($map)->select();

        if ($list) {
            foreach ($list as $key => $value) {
                if (!isset($group_list[$value['group_id']])) {
                    continue;
                }
                // 动态日封顶算力
                $max_num = $group_list[$value['group_id']]['dynamic_max_num'];

                /*------------------------------------------------------------------------------*/
                $child_num = isset($listChildNum[$value['id']]) ? $listChildNum[$value['id']] : 0;
                if ($child_num>0) {
                    // 下线代数
                    $child_num = $child_num>3 ? 3 : $child_num;
                    // 分享算力配置
                    $dynamic_rebate = [
                        1=>0.2,
                        2=>0.07,
                        3=>0.03,
                    ];
                    // 下线
                    $children = model('user')->getChildren($value['id'], $child_num);
                    // 算力
                    $total_money = 0;
                    for ($i=1; $i <= $child_num; $i++) {
                        if (!isset($children[$i])) {
                            break;
                        }
                        foreach ($children[$i] as $k => $v) {
                            if (!isset($group_list[$v['group_id']])) {
                                continue;
                            }
                            //              下线的智能宝 * 下线的静态算力比例                           * 当前用户的动态算力比例
                            $total_money += $v['score'] * $group_list[$v['group_id']]['static_rate']/100 * $dynamic_rebate[$i];
                        }
   
                    }

                    /*if ($total_money>$max_num) {
                        $total_money = $max_num;
                        $max_num = 0;
                    } else {
                        $max_num = $max_num - $total_money;
                    }*/
                    $all_money[2] = $total_money;
                }
                /*------------------------------------------------------------------------------*/

                // 共享算力
                if (isset($listTeamAmount[$value['id']])) {
                    $teamAmount = $listTeamAmount[$value['id']];
                    // 有业绩，且有小区业绩
                    if (isset($teamAmount['amount']) && count($teamAmount['amount'])==2) {
                        $total_money = min($teamAmount['amount'])*$share_rebate_rate;
                        // $total_money = $total_money>$max_num ? $max_num : $total_money;
                        $all_money[3] = $total_money;
                    }
                }

            }
        }



        $all_money[1] = isset($all_money[1]) ? money_format_new($all_money[1]) : '0.0000';
        $all_money[2] = isset($all_money[2]) ? money_format_new($all_money[2]) : '0.0000';
        $all_money[3] = isset($all_money[3]) ? money_format_new($all_money[3]) : '0.0000';

        $this->view->assign('all_money', $all_money);

        return $this->view->fetch();
    }


    /**
     * 交易界面
     */
    
    public function jiaoyi()
    {
        model('trade')->clear();
        $buy_list = db('order')->where('buyer_id', $this->auth->id)->select();
        $this->view->assign('buy_list', $buy_list);

        $sell_list = db('order')->where('seller_id', $this->auth->id)->select();
        $this->view->assign('sell_list', $sell_list);

        // 当前委托
        $map['user_id'] = $this->auth->id;
        // $map['balance'] = ['gt', 0];
        $map['status'] = 0;
        $trade_list = db('trade')->where($map)->order('id desc')->select();
        if ($trade_list) {
            foreach ($trade_list as $key => $value) {
                if ($value['type'] == 0) {
                    $where = [
                        'buyer_trade_id' => $value['id'],
                    ];
                }else{
                    $where = [
                        'seller_trade_id' => $value['id'],
                    ];
                }
                $where['status'] = ['neq', 3];
                $order = db('order')->where($where)->count();
                $trade_list[$key]['can_cancel'] = empty($order) ? 1 : 0;
            }
        }
        $this->view->assign('trade_list', $trade_list);

        // 历史委托
        // $map['balance'] = 0;
        $map['status'] = ['neq', 0];
        $history_list = db('trade')->where($map)->order('id desc')->select();
        $this->view->assign('history_list', $history_list);

        return $this->view->fetch(); 
    }

    /**
     *  委托详情界面
     */
    
    public function entrust_detail($id){

        $user_id = $this->auth->id;
        $id = (int)$id;
        $map = "(buyer_trade_id=$id and buyer_id=$user_id) or (seller_trade_id=$id and seller_id=$user_id)";
        $list = db('order')->where($map)->order('id desc')->select();
        if ($list) {
            foreach ($list as $key => $value) {
                $seller_mobile = db('user')->where('id', $value['seller_id'])->value('mobile');
                $list[$key]['seller_mobile'] = $seller_mobile;
            }
        }
        $this->view->assign('list', $list);


      return $this->view->fetch(); 
      
    }




    /**
     * 客服电话
     */
    
    public function servicetel(){
        
        $site = config("site"); 
        //print_r($site);exit;
        $this->view->assign('kf_qq',$site['kf_qq']);
        $this->view->assign('kf_tel',$site['kf_tel']);

        //获取id为14的一篇文章

         $map = [
                'id'       => 14,
            ];
         $art_info = db('article')->field('name,content')->where($map)->find();  

         //print_R($art_info);exit; 

        $this->view->assign('art_info', $art_info);

        return $this->view->fetch();  
    }


        /**
     * 设置界面
     */
    
    public function set(){

        return $this->view->fetch();  
    }


   /**
    * 修改登录密码
    */
   
    public function edit_login_pass()
    {
        return $this->view->fetch(); 
    }
   
   /**
    * 修改交易密码
    */
    public function edit_pay_pass()
    {


        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepaypwd($newpassword, $oldpassword);
            if ($ret) {
                $this->success(__('Reset pay password successful'), url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }


        return $this->view->fetch(); 
    }

   /**
    * 重置手机号码
    */
    public function edit_tel()
    {
        return $this->view->fetch(); 
    }
   
   /**
    * 绑定电子邮箱
    */
    public function bind_email()
    {
        return $this->view->fetch(); 
    }


    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $username = $this->request->post('mobile'); //hjl mod 8-13
            $user_code = model('User')->createUsername();
            $password = $this->request->post('password');
            $email = $this->request->post('email');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');

            $code = $this->request->post('code');

            $pay_password = $this->request->post('pay_password');
            $parent_id = $this->request->post('parent_id');
            $node_parent_id = $this->request->post('node_parent_id');


            $ret = Sms::check($mobile, $code, 'register');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'register');


            $rule = [
                'username'     => 'require|length:3,30',
                'password'     => 'require|length:6,30',
                'email'        => 'email',
                'mobile'       => 'regex:/^1\d{10}$/',
                'captcha'      => 'captcha',
                '__token__'    => 'token',

                'pay_password'   => 'require|length:6,30',
                'parent_id'      => 'require',
                'node_parent_id' => 'require',
            ];

            $msg = [
                'username.require'     => 'Username can not be empty',
                'username.length'      => 'Username must be 3 to 30 characters',
                'password.require'     => 'Password can not be empty',
                'password.length'      => 'Password must be 6 to 30 characters',
                'captcha.require'      => 'Captcha can not be empty',
                'captcha.captcha'      => 'Captcha is incorrect',
                'email'                => 'Email is incorrect',
                'mobile'               => 'Mobile is incorrect',

                'pay_password.require'   => 'PayPassword can not be empty',
                'parent_id.require'      => 'parent_id can not be empty',
                'node_parent_id.require' => 'node_parent_id can not be empty',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'email'     => $email,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                '__token__' => $token,
                
                'pay_password'   => $pay_password,
                'parent_id'      => $parent_id,
                'node_parent_id' => $node_parent_id,
            ];
            $extend = [
                'pay_password'   => $pay_password,
                'parent_id'      => $parent_id,
                'node_parent_id' => $node_parent_id,
                'user_code' => $user_code,
            ];
           
            $validate = new Validate($rule, $msg);
            //var_dump($validate);exit;
            //print_r($data);exit;
            $result = $validate->check($data);

            // 检查parent_id
            $parent_id = db('user')->where('user_code', $extend['parent_id'])->value('id');
            if (empty($parent_id)) {
                $this->error('推荐人不存在', null, ['token' => $this->request->token()]);
            }
            $extend['parent_username'] = $extend['parent_id'];
            $extend['parent_id'] = $parent_id;

            // 检查node_parent_id
            $node_parent_id = db('user')->where('user_code', $extend['node_parent_id'])->value('id');
            if (empty($node_parent_id)) {
                $this->error('接点人不存在', null, ['token' => $this->request->token()]);
            }
            $extend['node_parent_username'] = $extend['node_parent_id'];
            $extend['node_parent_id'] = $node_parent_id;
            $node_child_num = db('user')->where('node_parent_id', $extend['node_parent_id'])->count('id');
            if ($node_child_num >= 2) {
                $this->error('此接点人下面已无位置', null, ['token' => $this->request->token()]);
            }



            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
             
              // die('cccc');

            if ($this->auth->register($username, $password, $email, $mobile, $extend)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synregister($this->auth->id, $password);
                }
                $this->success(__('Sign up successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
    }

    $this->view->assign('url', $url);
    $this->view->assign('title', __('Register'));
    return $this->view->fetch();
}

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->success(__('You\'ve logged in, do not login again'), $url);
        if ($this->request->isPost()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $keeplogin = (int)$this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'account'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
                '__token__' => 'token',
            ];

            $msg = [
                'account.require'  => 'Account can not be empty',
                'account.length'   => 'Account must be 3 to 50 characters',
                'password.require' => 'Password can not be empty',
                'password.length'  => 'Password must be 6 to 30 characters',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogin($this->auth->id);
                }
                $this->success(__('Logged in successful') . $synchtml, $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
    }
    $this->view->assign('url', $url);
    $this->view->assign('title', __('Login'));
    return $this->view->fetch();
}

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $synchtml = '';
        ////////////////同步到Ucenter////////////////
        if (defined('UC_STATUS') && UC_STATUS) {
            $uc = new \addons\ucenter\library\client\Client();
            $synchtml = $uc->uc_user_synlogout();
        }
        $this->success(__('Logout successful') . $synchtml, url('user/index'));
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $userInfo = db('UserAuth')->where('user_id', $this->auth->id)->find();
        $this->view->assign('userInfo', $userInfo);

        $this->view->assign('title', __('Profile'));
        return $this->view->fetch('profile');
    }

    /**
     * hjl 忘记密码界面
     */

     public function forgetpwd(){

         return $this->view->fetch();
     }



    /**
     * 修改密码
     */
    public function changepwd()
    {
        if ($this->request->isPost()) {
            $oldpassword = $this->request->post("oldpassword");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $token = $this->request->post('__token__');
            $rule = [
                'oldpassword'   => 'require|length:6,30',
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'oldpassword'   => $oldpassword,
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
                '__token__'     => $token,
            ];
            $field = [
                'oldpassword'   => __('Old password'),
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            $ret = $this->auth->changepwd($newpassword, $oldpassword);
            if ($ret) {
                $synchtml = '';
                ////////////////同步到Ucenter////////////////
                if (defined('UC_STATUS') && UC_STATUS) {
                    $uc = new \addons\ucenter\library\client\Client();
                    $synchtml = $uc->uc_user_synlogout();
                }
                $this->success(__('Reset password successful') . $synchtml, url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        return $this->view->fetch();
    }

    // 财富宝转智能宝
    public function money2score()
    {

        if ($this->request->isPost()) {
            $amount = $this->request->post('amount');
            $code = $this->request->post('code');

            $rule = [
                'amount'            => 'require',
            ];

            $msg = [
                'amount.require'  => 'amount can not be empty',
            ];
            $data = [
                'amount'   => $amount,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }

            if ($amount <= 0) {
                $this->error(__('amount can not be empty'), null, ['token' => $this->request->token()]);
                return false;
            }


            // 余额不足
            if ($amount > $this->auth->money) {
                $this->error(__('Insufficient Balance'), null, ['token' => $this->request->token()]);
                return false;
            }

            // 验证支付密码
            $pay_password = $this->request->post('pay_password');
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }


            $user = $this->auth;
            $money_after = $user->money - $amount;
            // $date = date('Ymd');
            //写入日志
            model('MoneyLog')->create(['user_id' => $this->auth->id, 'money' => -$amount, 'before' => $user->money, 'after' => $money_after, 'memo' => '转入智能宝']);

            $score_after = $user->score + $amount;
            //写入日志
            // model('ScoreLog')->create(['user_id' => $this->auth->id, 'score' => $amount, 'before' => $user->score, 'after' => $score_after, 'memo' => '财富宝转入']);
            model('User')->score($amount, $this->auth->id, '财富宝转入');

            //更新会员信息
            // db('user')->where('id', $this->auth->id)->update(['money' => $money_after, 'score' => $score_after]);
            db('user')->where('id', $this->auth->id)->update(['money' => $money_after]);

            if (1) {
                
                $this->success(__('Operation completed'), url('user/money2score'));
            } else {
                $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
            }
        }

        return $this->view->fetch();
    }
    // 智能宝转财富宝
    public function score2money()
    {

        if ($this->request->isPost()) {
            $amount = $this->request->post('amount');
            $code = $this->request->post('code');

            $rule = [
                'amount'            => 'require',
            ];

            $msg = [
                'amount.require'  => 'amount can not be empty',
            ];
            $data = [
                'amount'   => $amount,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            if ($amount <= 0) {
                $this->error(__('amount can not be empty'), null, ['token' => $this->request->token()]);
                return false;
            }

            // 余额不足
            if ($amount > $this->auth->score) {
                $this->error(__('Insufficient Balance'), null, ['token' => $this->request->token()]);
                return false;
            }

            // 验证支付密码
            $pay_password = $this->request->post('pay_password');
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }

            $user = $this->auth;
            $score_after = $user->score - $amount;
            //写入日志
            // model('ScoreLog')->create(['user_id' => $this->auth->id, 'score' => -$amount, 'before' => $user->score, 'after' => $score_after, 'memo' => '转入财富宝']);
            model('User')->score(-$amount, $this->auth->id, '转入财富宝');

            $fee = config('site.score_to_money_fee') * $amount;

            $money_after = $user->money + $amount-$fee;
            // $date = date('Ymd');
            //写入日志
            model('MoneyLog')->create(['user_id' => $this->auth->id, 'money' => $amount, 'before' => $user->money, 'after' => $money_after, 'memo' => '智能宝转入']);

            //更新会员信息
            // db('user')->where('id', $this->auth->id)->update(['money' => $money_after, 'score' => $score_after]);
            db('user')->where('id', $this->auth->id)->update(['money' => $money_after]);

            // 扣除10%进入总矿池
            model('Config')->where('name', 'bkc_balance')->setInc('value', $fee);
            model('Config')->refreshFile();

            if (1) {
                
                $this->success(__('Operation completed'), url('user/score2money'));
            } else {
                $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
            }
        }

        return $this->view->fetch();
    }

    // 财富宝发送
    public function money_send($touid=0)
    {

        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $pay_password = $this->request->post('pay_password');
            $wallet_address = $this->request->post('wallet_address');
            $amount = $this->request->post('amount');
            $code = $this->request->post('code');

            $rule = [
                'username'       => 'require',
                'wallet_address' => 'require',
                'amount'            => 'require',
            ];

            $msg = [
                'username.require'  => 'Account can not be empty',
                'wallet_address.require'  => 'wallet_address can not be empty',
                'amount.require'  => 'amount can not be empty',
            ];
            $data = [
                'username'   => $username,
                'wallet_address'   => $wallet_address,
                'amount'   => $amount,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            // 余额不足
            if ($amount > $this->auth->money) {
                $this->error(__('Insufficient Balance'), null, ['token' => $this->request->token()]);
                return false;
            }
            $map = [
                'username'       => $username,
                'wallet_address' => $wallet_address,
            ];
            $account = db('user')->field('id')->where($map)->find();

            // 账户不存在
            if (empty($account)) {
                $this->error(__('Account not exist'), null, ['token' => $this->request->token()]);
                return false;
            }
            // 不能转账给自己
            if ($account['id'] == $this->auth->id) {
                $this->error(__('Can\'t transfer it to yourself'), null, ['token' => $this->request->token()]);
                return false;
            }
            
            // session('money_send_info', input('post.'));
            // $this->redirect('input_pass');

            // 验证支付密码
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }
            if (model('user')->moneyTransfer($this->auth->id, $account['id'], $amount)) {
                
                $this->success(__('Operation completed'), url('user/money_send'));
            } else {
                $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
            }
        }

        if ($touid>0) {
            $touser = db('user')->field('username, wallet_address')->where('id', $touid)->find();
            $this->view->assign('username', $touser['username']);
            $this->view->assign('wallet_address', $touser['wallet_address']);
        }

        return $this->view->fetch();
    }
    // 转账输入支付密码
/*    public function input_pass()
    {
        if (empty(session('money_send_info'))) {
            $this->error('转账信息错误，请检查', null, ['token' => $this->request->token()]);
        }

        if ($this->request->isPost()) {
            $post = session('money_send_info');
            $username = $post['username'];
            $pay_password = $this->request->post('pay_password');
            $wallet_address = $post['wallet_address'];
            $amount = $post['amount'];

            $rule = [
                'username'       => 'require',
                'wallet_address' => 'require',
                'amount'            => 'require',
            ];

            $msg = [
                'username.require'  => 'Account can not be empty',
                'wallet_address.require'  => 'wallet_address can not be empty',
                'amount.require'  => 'amount can not be empty',
            ];
            $data = [
                'username'   => $username,
                'wallet_address'   => $wallet_address,
                'amount'   => $amount,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }
            // 余额不足
            if ($amount > $this->auth->money) {
                $this->error(__('Insufficient Balance'), null, ['token' => $this->request->token()]);
                return false;
            }
            // 验证支付密码
            if (!$this->auth->checkpaypwd($pay_password)) {
                $this->error('支付密码不正确', null, ['token' => $this->request->token()]);
                return false;
            }
            $map = [
                'username'       => $username,
                'wallet_address' => $wallet_address,
            ];
            $account = db('user')->field('id')->where($map)->find();

            // 账户不存在
            if (empty($account)) {
                $this->error(__('Account not exist'), null, ['token' => $this->request->token()]);
                return false;
            }
            // 不能转账给自己
            if ($account['id'] == $this->auth->id) {
                $this->error(__('Can\'t transfer it to yourself'), null, ['token' => $this->request->token()]);
                return false;
            }
            if (model('user')->moneyTransfer($this->auth->id, $account['id'], $amount)) {
                session('money_send_info', null);
                $this->success(__('Operation completed'), url('user/money_send'));
            } else {
                $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
            }
        }

        return $this->view->fetch();
    }*/
    // 财富宝记录
    public function money_log()
    {
        $map = [
            'user_id' => $this->auth->id,
            // 'type' => 1,
        ];
        $logList = db('UserMoneyLog')->where($map)->field('type, money, memo, createtime, other_user_id')->order('createtime desc')->select();
       
        foreach($logList as $k=>$v){
           $logList[$k]['createtime'] = datetime($v['createtime']);

           $from_user = '';
           if ($v['other_user_id']>0) {
                $from_user = db('user')->where('id', $v['other_user_id'])->value('wallet_address');
           }
           $logList[$k]['from_user'] = $from_user;
        }

       // dump($logList);
        
        $this->view->assign('logList', $logList);
        return $this->view->fetch();
    }
    // 智能宝记录
    public function score_log()
    {
        $map = [
            'user_id' => $this->auth->id,
            // 'type' => 1,
        ];
        $logList = db('UserScoreLog')->where($map)->field('type, score, memo, createtime')->order('createtime desc')->select();
       
        foreach($logList as $k=>$v){
           $logList[$k]['createtime'] = datetime($v['createtime']);
        }

       //dump($logList);
        
        $this->view->assign('logList', $logList);
        return $this->view->fetch();
    }

    // 收款码
    public function wallet_qrcode()
    {
        $wallet_address = model('User')->createWalletAddress($this->auth->id);
        $this->view->assign('wallet_address', $wallet_address);

        $text = url('user/money_send', ['touid'=>$this->auth->id], true, true);
        $text = urlencode($text);
        $qrcode = '/qrcode/build?text='.$text.'&label=&logo=1&labelhalign=0&labelvalign=3&foreground=%23ffffff&background=%23000000&size=300&padding=10&logosize=50&labelfontsize=14&errorcorrection=medium';
        $this->view->assign('qrcode', $qrcode);
        return $this->view->fetch();
    }

    // 实名认证
    public function auth_status()
    {


        $auth = db('UserAuth')->where('user_id', $this->auth->id)->find();

        if (!empty($auth)) {
            if ($auth['status_data']!=2) {
                $this->redirect('index/index');
            }
            $this->assign('auth', $auth);
        }


        if ($this->request->isPost()) {
            $code = $this->request->post('code');

            $real_name = $this->request->post('real_name');
            $id_card = $this->request->post('id_card');
            $bank_name = $this->request->post('bank_name');
            $branch_bank_name = $this->request->post('branch_bank_name');
            $bank_card = $this->request->post('bank_card');

            if (!validation_filter_id_card($id_card)) {
                $this->error('请填写正确的身份证号码', null, ['token' => $this->request->token()]);
                return false;
            }


            $upload = $this->upload('id_image1_pic');
            if ($upload) {
                $id_image1_pic = $upload;
            } else {
                $id_image1_pic = isset($auth['id_image1_pic']) ? $auth['id_image1_pic'] : '';
            }
            $upload = $this->upload('id_image2_pic');
            if ($upload) {
                $id_image2_pic = $upload;
            } else {
                $id_image2_pic = isset($auth['id_image2_pic']) ? $auth['id_image2_pic'] : '';
            }
            $upload = $this->upload('id_image3_pic');
            if ($upload) {
                $id_image3_pic = $upload;
            } else {
                $id_image3_pic = isset($auth['id_image3_pic']) ? $auth['id_image3_pic'] : '';
            }

            $rule = [
                'real_name'        => 'require',
                'id_card'          => 'require',
                'bank_name'        => 'require',
                'branch_bank_name' => 'require',
                'bank_card'        => 'require',
                'id_image1_pic'    => 'require',
                'id_image2_pic'    => 'require',
                'id_image3_pic'    => 'require',
            ];

            $msg = [
                'real_name.require'        => '真实姓名不能为空',
                'id_card.require'          => '证件号码不能为空',
                'bank_name.require'        => '开户银行不能为空',
                'branch_bank_name.require' => '开户支行不能为空',
                'bank_card.require'        => '银行卡号不能为空',
                'id_image1_pic.require'    => '请上传身份证正面照片',
                'id_image2_pic.require'    => '请上传身份证反面照片',
                'id_image3_pic.require'    => '请上传身份证手持照片',
            ];
            $data = [
                'real_name'        => $real_name,
                'id_card'          => $id_card,
                'bank_name'        => $bank_name,
                'branch_bank_name' => $branch_bank_name,
                'bank_card'        => $bank_card,
                'id_image1_pic'    => $id_image1_pic,
                'id_image2_pic'    => $id_image2_pic,
                'id_image3_pic'    => $id_image3_pic,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return false;
            }


            if (empty($auth)) {
                $data['user_id'] = $this->auth->id;
                model('UserAuth')->save($data);
            } else {
                $data['status_data'] = 0;
                db('UserAuth')->where('id', $auth['id'])->update($data);
            }


            if (1) {
                
                $this->success(__('Operation completed'), url('user/to_auth'));
            } else {
                $this->error(__('Operation failed'), null, ['token' => $this->request->token()]);
            }
        }

        return $this->view->fetch();
    }

    // 去认证
    public function to_auth()
    {
        $auth = db('UserAuth')->field('status_data')->where('user_id', $this->auth->id)->find();
        $status = isset($auth['status_data']) ? $auth['status_data'] : -1;
        $this->assign('status', $status);

        $status_arr = [
            '-1' => '未认证',
            '0' => '待审核',
            '1' => '已认证',
            '2' => '审核失败',
        ];
        $this->assign('status_text', $status_arr[$status]);


        return $this->view->fetch();
    }

    // 收款信息
    public function shoukuan()
    {

        if ($this->request->isPost()) {

            $alipay_account = $this->request->post('alipay_account');
            $wechat_account = $this->request->post('wechat_account');

            $upload = $this->upload('alipay_pic');
            if ($upload) {
                $alipay_pic = $upload;
            } else {
                $alipay_pic = !empty($this->auth->alipay_pic) ? $this->auth->alipay_pic : '';
            }

            $upload = $this->upload('wechat_pic');
            if ($upload) {
                $wechat_pic = $upload;
            } else {
                $wechat_pic = !empty($this->auth->wechat_pic) ? $this->auth->wechat_pic : '';
            }


            $data = [
                'alipay_account' => $alipay_account,
                'wechat_account' => $wechat_account,
                'alipay_pic'     => $alipay_pic,
                'wechat_pic'     => $wechat_pic,
            ];

            $data = array_filter($data);
            if (empty($data)) {
                $this->error('请填写收款信息', null, ['token' => $this->request->token()]);
                return false;
            }

            db('User')->where('id', $this->auth->id)->update($data);

            $this->success(__('Operation completed'), url('user/index'));
        }

        return $this->view->fetch();
    }


}
